package domain

import (
	"album/dao"
	"album/model"
	"album/repo"
	"context"
	"errors"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"grpc-common/album/types/album"
	"listenboos-common/db"
)

type TrackInfoDomain struct {
	trackInfoRepo repo.TrackInfoRepo
}

func (d *TrackInfoDomain) SaveTrackInfo(ctx context.Context, conn db.DBConn, in *album.SaveTrackReq) (int64, error) {
	var data model.TrackInfo
	err := copier.Copy(&data, &in)
	if err != nil {
		return 0, err
	}
	if in.TrackId != 0 {
		data.Id = in.TrackId
	}
	id, err := d.trackInfoRepo.SaveTrackInfo(ctx, conn, &data)
	if err != nil {
		return 0, err
	}
	return id, nil
}
func (d *TrackInfoDomain) FindTrackByAlbumId(ctx context.Context, albumId int64, pageNo string, pageSize string) (tracks []*model.TrackInfo, current int64, Size int64, total, pages int64, err error) {
	tracks, current, Size, total, pages, err = d.trackInfoRepo.FindTrackByAlbumId(ctx, albumId, pageNo, pageSize)
	if err != nil {
		logx.Error(err)
		return nil, 0, 0, 0, 0, errors.New("数据库异常")
	}
	return tracks, current, Size, total, pages, nil
}
func (d *TrackInfoDomain) FindAlbumByUserId(ctx context.Context, in *album.FindUserTrackPageReq) (tracks []*model.TrackInfo, err error) {
	tracks, err = d.trackInfoRepo.FindAlbumByUserId(ctx, in.UserId, in.PageNum, in.PageSize)
	if err != nil {
		logx.Error(err)
		return nil, errors.New("数据库异常")
	}
	return tracks, nil
}

func (d *TrackInfoDomain) FindTrackByIdAndUserId(ctx context.Context, trackId int64) (track *model.TrackInfo, err error) {
	track, err = d.trackInfoRepo.FindAlbumByIdAndUserId(ctx, trackId)
	if err != nil {
		logx.Error(err)
		return nil, errors.New("数据库异常")
	}
	return track, err
}

func (d *TrackInfoDomain) DeleteTrackInfo(ctx context.Context, conn db.DBConn, in *album.RemoveTrackInfoReq) error {
	err := d.trackInfoRepo.DeleteTrackInfo(ctx, conn, in.TrackId, in.UserId)
	if err != nil {
		logx.Error(err)
		return errors.New("数据库异常")
	}
	return nil
}

func (d *TrackInfoDomain) FindGeTrack(ctx context.Context, trackId int64) ([]*model.TrackInfo, int64, error) {
	ts, aid, err := d.trackInfoRepo.FindGeTrack(ctx, trackId)
	if err != nil {
		logx.Error(err)
		return nil, 0, errors.New("数据库异常")
	}
	return ts, aid, nil
}

func (d *TrackInfoDomain) FindTrackInCount(ctx context.Context, trackId int64, trackCount int64) ([]*model.TrackInfo, error) {
	ts, err := d.trackInfoRepo.FindTrackInCount(ctx, trackId, trackCount)
	if err != nil {
		logx.Error(err)
		return nil, errors.New("数据库异常")
	}
	return ts, nil
}

func NewTrackInfoDomain(db *db.ListenDB) *TrackInfoDomain {
	return &TrackInfoDomain{
		trackInfoRepo: dao.NewTrackInfoDao(db),
	}
}
